import axios from 'axios'
import qs from 'qs'
// import { useRouter } from 'vue-router'
import router from './router'
// const router = useRouter()
import { ElMessageBox } from 'element-plus'

// axios.defaults.baseURL = ''  //正式
axios.defaults.baseURL = 'http://localhost:3000/api' //测试

//post请求头
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'
//允许跨域携带cookie信息
// axios.defaults.withCredentials = true
//设置超时
// axios.defaults.timeout = 15000;

// 添加请求拦截器
axios.interceptors.request.use(
  (config) => {
    // 在发送请求之前做些什么
    const accessToken = localStorage.getItem('token')
    if (accessToken) {
      config.headers['Authorization'] = `Bearer ${accessToken}`
    }
    return config
  },
  // 对请求错误做些什么
  (error) => Promise.reject(error)
)
// console.log(axios.interceptors.request)
// console.log(axios.interceptors.response)
// 添加响应拦截器
axios.interceptors.response.use(
  (response) => response,
  // 对响应错误做点什么
  (error) => {
    if (error.response && error.response.status === 401) {
      console.log('刷新')
      // router.replace({ name: 'login' })
      ElMessageBox.confirm('进行此操作请先登录, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        center: true
      })
        .then(() => {
          router.push({ name: 'login' })
        })
        .catch(() => {})
    }
  }
)

export default {
  /**
   * @param {String} url
   * @param {Object} data
   * @returns Promise
   */
  post(url, data) {
    return new Promise((resolve, reject) => {
      axios({
        method: 'post',
        url,
        data: qs.stringify(data)
      })
        .then((res) => {
          resolve(res.data)
        })
        .catch((err) => {
          reject(err)
        })
    })
  },

  get(url, data) {
    return new Promise((resolve, reject) => {
      axios({
        method: 'get',
        url,
        params: data
      })
        .then((res) => {
          // console.log('成功', res)
          resolve(res.data)
        })
        .catch((err) => {
          reject(err)
        })
    })
  }
}
